package com.zhouyibike.uu.util;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by dzyy on 2015/12/30.
 */
public class CommonHelper {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mgr.getActiveNetworkInfo();
        if (info != null && info.getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }

        return false;
    }


    //转换Bitmap的方法
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    //dip转换成px
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    //px转换成dp的方法
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
//
//    public static String downLoadFile(String urlPath, String fileName) {
//        URL url = null;
//        try {
//            url = new URL(urlPath);
//        } catch (MalformedURLException e) {
//            return "";
//        }
//
//        URLConnection con = null;
//        try {
//            con = url.openConnection();
//        } catch (IOException e) {
//            return "";
//        }
//        try {
//            InputStream is = con.getInputStream();
//            String dirName = getApplicationCachePath() + "/MedicalRecordTemp/";
//            File f = new File(dirName);
//            if (!f.exists()) {
//                f.mkdir();
//            }
//
//            String newFilename = dirName + fileName;
//            File file = new File(newFilename);
//            if (file.exists()) {
//                file.delete();
//            }
//            try {
//                byte[] bs = new byte[1024];
//                int len;
//                OutputStream os = new FileOutputStream(newFilename);
//                while ((len = is.read(bs)) != -1) {
//                    os.write(bs, 0, len);
//                }
//                os.close();
//                is.close();
//
//                return newFilename;
//            } catch (Exception e) {
//                return "";
//            }
//        } catch (IOException e) {
//            return "";
//        }
//    }


    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9,.]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    //将字符串转换成Bitmap类型
    public static Bitmap stringtoBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    //将Bitmap转换成字符串
    public static String bitmaptoString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }


    /**
     * <br>功能简述:4.4及以下从相册获取图片路径的方法
     */
    public static String selectImage(Context context, Intent data) {
        Uri selectedImage = data.getData();
        if (selectedImage != null) {
            String uriStr = selectedImage.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                return null;
            }
        }
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }


    /**
     * <br>功能简述:4.4及以上从相册获取图片路径的方法
     * <br>功能详细描述:
     * <br>注意:
     *
     * @param context
     * @param uri
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    //传入图片路径获得缩略图
    public static Bitmap getImageThumbnail(String imagePath) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / 150;
        int beHeight = h / 150;
        int be = 1;
        if (beWidth > beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        return bitmap;
    }


    /**
     * 保存Bitmap图片为本地文件
     */
    public static void saveFile(Bitmap bitmap, String filename) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filename);
            if (fileOutputStream != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }

    }


    //传入一个view取得bitmap，这里实现了截屏功能
    public static Bitmap getViewBitmap(View v) {
        v.clearFocus(); //
        v.setPressed(false); //
        // 能画缓存就返回false
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }





    /***
     * 根据资源文件获取Bitmap
     */
    public static Bitmap ReadBitmapByPath(String path, int screenWidth, int screenHight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inInputShareable = true;
        options.inPurgeable = true;
        FileInputStream stream = null;
        Bitmap bitmap = null;
        try {
            stream = new FileInputStream(new File(path));
            bitmap = BitmapFactory.decodeStream(stream, null, options);
        } catch (Exception e) {
        }
//        InputStream stream = new InputStream();
        return getBitmap(bitmap, screenWidth, screenHight);
    }

    /***
     * 等比例压缩图片
     *
     * @param bitmap
     * @param screenWidth
     * @param screenHight
     * @return
     */
    public static Bitmap getBitmap(Bitmap bitmap, int screenWidth,
                                   int screenHight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth);
        Matrix matrix = new Matrix();
        float scale = (float) screenWidth / w;
        float scale2 = (float) screenHight / h;

        // scale = scale < scale2 ? scale : scale2;

        // 保证图片不变形.
        matrix.postScale(scale, scale);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage   ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

//
//    //MaterialIconView设置点击和抬起时候的颜色
//    public static void setMaterialIconViewSelected(final MaterialIconView view, final int color) {
//        view.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        view.setColor(LYApplication.currentActivity.getResources().getColor(R.color.bggray));
//                        break;
//
//                    case MotionEvent.ACTION_UP:
//                        view.setColor(color);
//                        break;
//                }
//
//                return false;
//            }
//        });
//    }


    //判断如果EditText为空返回false并且使其获得焦点，并且弹出小键盘。
//    public static boolean setFocusable2EditText(EditText editText) {
//        String txt = editText.getText().toString().trim();
//        if (TextUtils.isEmpty(txt)) {
//            editText.setFocusable(true);
//            editText.requestFocus(); //请求获取焦点
//            editText.setSelection(editText.getText().toString().length());
//            InputMethodManager imm = (InputMethodManager) LYApplication.currentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//            return false;
//        }
//        return true;
//    }
//
//
//    public static TextView createTextView(Context context, String text, int color, float width, float height, int textSize) {
//        TextView textView = new TextView(context);
//        textView.setText(text);
//        textView.setWidth(CommonHelper.dip2px(LYApplication.currentActivity, width));
//        textView.setHeight(CommonHelper.dip2px(LYApplication.currentActivity, height));
//        textView.setGravity(Gravity.CENTER);
//        float d = context.getResources().getDimensionPixelSize(textSize);
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, d);
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        lp.setMargins(0, 0, 10, 0);
//        textView.setLayoutParams(lp);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            textView.setTextColor(context.getColor(R.color.colorWhite));
//            textView.setBackgroundColor(context.getColor(color));
//        } else {
//            textView.setTextColor(context.getResources().getColor(R.color.colorWhite));
//            textView.setBackgroundColor(context.getResources().getColor(color));
//        }
//        return textView;
//    }
//
//    public static TextView createTextViewDraw(Context context, String text, float width, float height, int textSize, int draw) {
//        TextView textView = new TextView(context);
//        textView.setText(text);
//        textView.setWidth(CommonHelper.dip2px(LYApplication.currentActivity, width));
//        textView.setHeight(CommonHelper.dip2px(LYApplication.currentActivity, height));
//        textView.setGravity(Gravity.CENTER);
//
//        float d = context.getResources().getDimensionPixelSize(textSize);
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, d);
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        lp.setMargins(0, 0, 10, 0);
//        textView.setLayoutParams(lp);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            textView.setTextColor(context.getColor(R.color.colorWhite));
//            textView.setBackground(context.getDrawable(draw));
//        } else {
//            textView.setTextColor(context.getResources().getColor(R.color.colorWhite));
//            textView.setBackgroundDrawable(context.getResources().getDrawable(draw));
//        }
//        return textView;
//    }


    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }
//
//
//    //返回过滤条件的方法
//    public static Map<String, String> getFilter(String filterCode) {
//        Map<String, String> filterMap = new HashMap<>();
//        if (DataCache.getInstance().getServerConfigs().containsKey(filterCode)) {
//            String value = DataCache.getInstance().getServerConfigs().get(filterCode).get(0).CONFIGVALUE;
//            String[] points = value.split(";");
//            List<String> list = Arrays.asList(points);
//            for (int i = 0; i < list.size(); i++) {
//                String[] maps = list.get(i).split(",");
//                String key = maps[0];
//                String mvalue = "";
//                if (maps != null && maps.length == 2) {
//                    mvalue = maps[1];
//                }
//                filterMap.put(key, mvalue);
//            }
//        }
//        return filterMap;
//    }


    //图片着色
    public static Drawable tintDrawable(Context context,int draw, ColorStateList colors) {
        Drawable originBitmapDrawable = context.getResources().getDrawable(draw);
        final Drawable wrappedDrawable = DrawableCompat.wrap(originBitmapDrawable);
        DrawableCompat.setTintList(wrappedDrawable, colors);
        return wrappedDrawable;
    }
    /**
     * @param str  分割字符串的符号
     * @param list
     * */
    public static String list2String(List<String> list, String str) {
        String text = "";
        for (int i = 0; i < list.size(); i++) {
            text += list.get(i);
            if (!(i + 1 == list.size())) {
                text += str;
            }
        }
        return text;
    }

}
